#!/usr/bin/env python
#coding=utf-8

#This file for XCMD, created by OpenThings.
#Using this to automate the test procedure.
#Author: openthings@163.com. copyright&GPL V2.
#Last modified 2014-11-03.

import serial
import time

isSimulate = 1
port = '/dev/ttyUSB0'
baudrate = 9600

ser = serial.Serial()

def serialopen():
	if isSimulate <> 1:
		ser.port = port
		ser.baudrate = baudrate
		#ser.timeout = 1
		ser.rtscts = 0
		ser.open()
		
def sayhello():
	strline = xcmd2("@")
	print ">> ",strline

def readline():
	strline = ser.readline()
	return strline
	
def write(strCMD):
	if isSimulate==1:
		print strCMD,
	else:
		#print "XWRITE",strCMD
		ser.write(strCMD)

def writeln(strCMD):
	if isSimulate==1:
		print strCMD
	else:
		ser.write(strCMD+"\r\n")

#等待一行结束，如果等到了立即返回。
def waitline():
	while(1):
		strline = ser.readline()
		if strline != "":
			#print "R-CMD:",strlineCMD
			break
	return strline

#等待一直到“>”出现为止，一共试给定次数（20）。
#最多可以读20行返回值，如果返回值多，可以修改到更大。
def waitmore():
	i=0
	strResult=""
	while(i<=20):
		strline = ser.readline()
		if strline.find(">")>=0:	#没有回车换行，只有超时才会返回。
			break
		if strline <> "":
			strResult += strline 
		i+=1
		#print i
	#print "RESP: ",	strResult
	return strResult

def waitresult():
	waitline()
	return waitmore()
		
def waitstart():
	while(1):
		strline = ser.readline()
		print strline,
		if strline.find("Lua")>0:
			print ">>Started.=============="
			break
		
#cmd执行，会返回一行或多行。
#调用返回有两种：返回值，输出信息方式。
def xcmd_all(strCMD):
	if isSimulate==1:
		print strCMD
	else:
		writeln(strCMD)
		strResult = waitresult()
		return strResult

def xcmd1(strCMD):
	if isSimulate==1:
		print strCMD
	else:
		writeln(strCMD)
		strResult = waitline()
		return strResult

def xcmd2(strCMD):
	if isSimulate==1:
		print strCMD
	else:
		ser.write(strCMD+"\r\n")
		strResponse = waitline()
		strResult = waitline()
		return strResult

def xcmd3(strCMD):
	if isSimulate==1:
		print strCMD
	else:
		ser.write(strCMD+"\r\n")
		strResponse = waitline()
		strStatus = waitline()
		strResult = waitline()
		return strResult
		
def serialclose():
	if isSimulate!=1:
		ser.close()
